package com.ash.android_adk_demo
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi
import com.ash.android_adk_demo.databinding.ActivityPsyBinding
import com.ash.base.logd
import com.ash.psyalgorithm.PsyAlgorithmPlugin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random

@RequiresApi(Build.VERSION_CODES.O)
class PsyActivity : ComponentActivity(), OnClickListener {

    val TAG = "PsyActivity"
    var psyRun = false
    val macDeviceId= "hwb_dev_ss"

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
    }

    val binding by lazy{ ActivityPsyBinding.inflate(layoutInflater)}

    val psyPlugin: PsyAlgorithmPlugin by lazy{
        PsyAlgorithmPlugin.getInstance()
    }

    fun bindClick() {
        binding.let{
            it.btnPsyBind.setOnClickListener(this)
            it.btnPsyStart.setOnClickListener(this)
            it.btnPsyStop.setOnClickListener(this)
        }
    }

    fun initPsy(){
        psyPlugin.setHeartRateListener { heartBean ->
            "${heartBean.heartRate},${heartBean.heartRateTenAvg},${heartBean.meanRate}".logd(
                "heartRate: "
            )
        }

        psyPlugin.setHrvListener { hrvModel -> hrvModel.toJson().toString().logd("hrv: ") }

        psyPlugin.setWaveResultListener { waveResult -> waveResult.toString().logd("waveResult: ") }

        psyPlugin.setMainIndicatorListener { indicators ->
            indicators.toString().logd("mainIndicator: ")
        }
    }

    @RequiresApi(Build.VERSION_CODES.P)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "onCreate: ")
        try {
            setContentView(binding.root)
            bindClick()
            initPsy()
        } catch (e: Exception) {
            "${e.message}".logd()
        }
    }

    fun toast(msg: String) {
        runOnUiThread{
            Toast.makeText(applicationContext, "$TAG:$msg", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_psy_bind -> {
                GlobalScope.launch {
                    var b = psyPlugin.checkAndBindDevice(
                        this@PsyActivity,
                        macDeviceId
                    )
                    withContext(Dispatchers.Main){
                        binding.tvPsyStatus.text = "绑定：" + if (b == true) "成功" else "失败"
                    }
                }
            }
            R.id.btn_psy_start -> {
                var b = psyPlugin.initialize(this)
                if (b==false){
                    toast("初始化失败，没有权限")
                    return
                }
                psyRun = true
                GlobalScope.async {
                    var lastValue = 80.0.toFloat()
                    val startTime = System.currentTimeMillis() * 1000
                    while (psyRun == true) {
                        delay(1000)
                        val newValue = (lastValue + Random.nextInt(-10,20))
                        val timestamp = System.currentTimeMillis()
                        psyPlugin.addHeartRateData(60000 / newValue.toInt(), timestamp)
                        "Added data: $newValue at $timestamp".logd()
                    }
                }
            }
            R.id.btn_psy_stop -> {
                psyRun = false
                psyPlugin.cleanup(this)
            }
        }
    }
}
